package Midium;

import java.util.ArrayList;
import java.util.List;

//47.全排列II
//允许重复数字，结果不允许有重复的
public class Solution47 {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> resList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        __permute(list, nums, 0, resList);
        return resList;
    }

    //固定一个数，递归的排列后面的数
    public void __permute(List<Integer> list, int[] nums, int index, List<List<Integer>> resList) {
        for (int i = index; i < nums.length; i++) {
            //nums[i]交换顺序到第一个位置,index为起始位置
            int temp = nums[i];
            nums[i] = nums[index];
            nums[index] = temp;
            list.add(nums[index]);
            if (list.size() == nums.length) {
                //去重
                boolean flag = true;
                for (List<Integer> l : resList) {
                    int p = 0;
                    Integer[] arr = new Integer[l.size()];
                    l.toArray(arr);
                    Integer[] lA = new Integer[list.size()];
                    list.toArray(lA);
                    while (p < l.size()) {
                        if (lA[p] != arr[p]) {
                            break;
                        } else p++;
                    }

                    if (p == nums.length) {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                    resList.add(new ArrayList<>(list));

            }
            __permute(list, nums, index + 1, resList);
            //用完以后先换回来，再去掉
            temp = nums[i];
            nums[i] = nums[index];
            nums[index] = temp;
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        Solution47 s47 = new Solution47();
        List<List<Integer>> permute = s47.permuteUnique(new int[]{1, 1, 3});
        for (List<Integer> list : permute) {
            System.out.print("[");
            for (int a : list) {
                System.out.print(a + ",");
            }
            System.out.println("]");
        }
    }
}
